package com.toutiao.issue

import scala.collection.mutable.ArrayBuffer
import org.elasticsearch.common.settings.{Settings,ImmutableSettings}
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.index.query.FilterBuilders._
import org.elasticsearch.action.search.SearchType
import org.elasticsearch.common.unit.TimeValue
import net.liftweb.json.JsonAST
import net.liftweb.json.Extraction
import net.liftweb.json.Printer
import net.liftweb.json.JsonDSL._
import net.liftweb.json.parse
import java.util.Date
import org.apache.log4j.Logger

class MapStore (
		esName:String,
		esUri:String,
		esPort:Int,
		esIndex:String,
		esSchema:String
    ) {
  
  private
  val _log = Logger.getLogger(this.getClass.getName)
  _log.info("esName "+esName)
  _log.info("esURI "+esUri)
  _log.info("esPort "+esPort)
  _log.info("esIndex "+esIndex)
  
  private
  val s = ImmutableSettings.settingsBuilder().
  			put("cluster.name",esName).build()
  
  private
  val ES = new TransportClient(s).addTransportAddress(
		  	new InetSocketTransportAddress(esUri,esPort))
  _log.info(ES.listedNodes())
  
  implicit val _ = net.liftweb.json.DefaultFormats  
  
  def _init(name:String, v:String, ct:Date, ut:Date) = {
    val z = ("NAME"->name)~("VALUE"->v)~("CREATE_TIME"->SimpleDate.format(ct))~("UPDATE_TIME"->SimpleDate.format(ut))
    z
  }
  
  def insert(name:String, v:String, ct:Date, ut:Date) = {
    val line = Printer.compact(JsonAST.render(_init(name,v,ct,ut)))
    val indexName = esIndex
    ES.prepareIndex(indexName,esSchema,name).setSource(line).execute.actionGet
  }
  
  def insert(ns:Array[(String,String,Date,Date)]) {
    val bulkRequest = ES.prepareBulk
    ns.foreach(n => {
      val name = n._1
      val v = n._2
      val ct = n._3
      val ut = n._4
      val indexName = esIndex    
      val line = Printer.compact(JsonAST.render(_init(name,v,ct,ut)))
      val m = ES.prepareIndex(indexName,esSchema,name).setSource(line)
      bulkRequest.add(m)
    })
    bulkRequest.execute.actionGet    
  }
  
  def close = ES.close
  
}
